import { validateParam } from '../../validate/validate.js';
import { userLogin } from '../../apis/index.js';

Page({
  data: {
    typeuname: "info",
    typepd: "info",
    unamecolor: '#ff4d4d',
    pdcolor: "#ff4d4d",
    username: "",
    password: "",
    isshow:"显示",
    pdtype:"password"
  },
  isShow:function(){
    const isshow = this.data.pdtype === "password" 
    this.setData({
      isshow:isshow ? "隐藏":"显示",
      pdtype:isshow ? "safe-password":"password"
    })
  },

  handleUname(e) {
    const value = e.detail.value;
    this.setData({
      username: value,
      typeuname: value.length > 0 ? "success" : "info",
      unamecolor: value.length > 0 ? "#00b26a" : '#ff4d4d'
    });
  },

  handlePd(e) {
    const value = e.detail.value;
    this.setData({
      password: value,
      typepd: value.length > 7 ? "success" : "info",
      pdcolor: value.length > 7 ? "#00b26a" : '#ff4d4d'
    });
  },

  userLogin() {
    const { username, password } = this.data;
    
    if (!validateParam({ username, password })) return;

    userLogin(username, password)
      .then((res) => {
        console.log('成功',res);
        const userInfo = {
          username:res.data.msg.username,
          email:res.data.msg.email,
          last_name:res.data.msg.last_name,
          phone_number:res.data.msg.phone_number
        }
        console.log(userInfo);
        console.log(userInfo.email);
        console.log(userInfo.username);
        console.log(userInfo.phone_number);
        console.log(userInfo.last_name);
        wx.setStorageSync('userInfo', userInfo)
        wx.showToast({
          title: `登录成功`,
          icon: "none",
          duration: 2000
        });
        wx.setStorageSync('token', res.data.msg.token)
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/mine/mine',
          })
        }, 2000);
        // 登录成功后跳转页面保存用户名和token到本地
      })
      .catch((error) => {
        console.log('错误',error);
        const { statusCode } = error;
        let message = '网络错误，请稍后再试';
        if (statusCode === 401) {
          message = '账号或密码错误';
        }
        wx.showToast({
          title: message,
          icon: "none",
          duration: 2000
        });
      });
  },

  // 可删除不需要的生命周期函数
  // onLoad(options) { },
  // onReady() { },
  // onShow() { },
  // onHide() { },
  // onUnload() { },
  // onPullDownRefresh() { },
  // onReachBottom() { },
  // onShareAppMessage() { }
});
